#!/bin/bash

# 日志文件
LOG_FILE="/logs/voice-record-monitor.log"

# 时间戳
TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")

# 检查CPU负载
CPU_LOAD=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d. -f1)
MEMORY_USAGE=$(free -m | awk '/Mem:/ {print $3}')
MEMORY_TOTAL=$(free -m | awk '/Mem:/ {print $2}')
MEMORY_PERCENT=$((MEMORY_USAGE * 100 / MEMORY_TOTAL))

echo "$TIMESTAMP - 当前CPU使用率: $CPU_LOAD%, 内存使用: $MEMORY_PERCENT%" >> $LOG_FILE

# 检查服务状态
SERVICE_STATUS=$(systemctl is-active voice-record)

if [ "$SERVICE_STATUS" != "active" ]; then
    echo "$TIMESTAMP - 服务不在运行状态，正在重启..." >> $LOG_FILE
    systemctl restart voice-record
    echo "$TIMESTAMP - 服务已重启" >> $LOG_FILE
fi

# 如果CPU负载大于75%或内存使用超过80%，重启服务
if [ $CPU_LOAD -gt 75 ] || [ $MEMORY_PERCENT -gt 80 ]; then
    echo "$TIMESTAMP - 资源使用率过高(CPU: $CPU_LOAD%, 内存: $MEMORY_PERCENT%)，正在重启服务..." >> $LOG_FILE
    systemctl restart voice-record
    echo "$TIMESTAMP - 服务已重启" >> $LOG_FILE
fi

# 检查网站可访问性
HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" https://localhost:443 -k --connect-timeout 5)

if [ "$HTTP_STATUS" != "200" ] && [ "$HTTP_STATUS" != "302" ] && [ "$HTTP_STATUS" != "301" ]; then
    echo "$TIMESTAMP - 网站无法访问(HTTP状态码: $HTTP_STATUS)，正在重启服务..." >> $LOG_FILE
    systemctl restart voice-record
    echo "$TIMESTAMP - 服务已重启" >> $LOG_FILE
fi 